package d;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 86183
 * Date: 2024-04-28
 * Time: 8:28
 */
public class TcpEchoServer {
    private ServerSocket socket = null;
    public TcpEchoServer(int port) throws IOException {
        socket = new ServerSocket(port);

    }
    public void start() throws IOException {
        System.out.println("服务器启动!");
        ExecutorService pool = Executors.newCachedThreadPool();
        while(true){
            Socket clientSocket = socket.accept();
//            processConnection(clientSocket);
            pool.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(clientSocket);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            });

//            Thread t = new Thread(()->{
//                try {
//                    processConnection(clientSocket);
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            });
//            t.start();

        }
    }

    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s : %d ] ,客户端上线\n",clientSocket.getInetAddress(),clientSocket.getPort());
        try(InputStream inputStream = clientSocket.getInputStream();
            OutputStream outputStream = clientSocket.getOutputStream()){
            Scanner scanner = new Scanner(inputStream);
            while(true){

                if(!scanner.hasNext()){
                    System.out.printf("[%s : %d ],客户端下线\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                //从客户端获取请求
               String request = scanner.next();
                //根据请求计算响应
               String response =  process(request);
               //将请求写回客户端
                outputStream.write(response.getBytes());
                System.out.printf("[%s : %d ],req = %s,resp = %s",clientSocket.getInetAddress(),clientSocket.getPort(),
                        request,response);
            }

        }finally {
            clientSocket.close();
        }
    }

    public String process(String request) {

        return request+"\n";
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer tcpEchoServer = new TcpEchoServer(9090);
        tcpEchoServer.start();
    }
}
